package com.cubesugar2014.withchild;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.cubesugar2014.withchild.MainActivity;
import com.cubesugar2014.withchild.R;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.app.ActivityManager.RecentTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.telephony.SmsManager;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

public class SService extends Service implements LocationListener {

	
	static public void FLOG(String text)
	{       
/*	   File logFile = new File("sdcard/log_wc.txt");
	   if (!logFile.exists())
	   {
	      try
	      {
	         logFile.createNewFile();
	      } 
	      catch (IOException e)
	      {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }
	   }
	   try
	   {
	      //BufferedWriter for performance, true to set append to file flag
	      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
	      buf.append(text);
	      buf.newLine();
	      buf.flush();
	      buf.close();
	   }
	   catch (IOException e)
	   {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	   }
	*/
	}
	
	public boolean _sendSMS(String message) {  
	    	
		if (message.equals(mSentPrevMessage) && mActivateTick - mSentTick < MINIMUM_RESENT_GAP )
		{
			return false;
		}
		
		
		FLOG("send sms " + message);
				
    	String phone = mSettings.getString("phoneNumber","");
    	
    	if (phone == null || phone.isEmpty())
    		return false;
    	
		
    	FLOG("phone : " + phone);
		
    	SmsManager smsManager = SmsManager.getDefault();
    	String sendTo = phone;
    	
    	FLOG("divideMessage : " + message);
    	
    	ArrayList<String> partMessage = smsManager.divideMessage(message);
    	
    	FLOG("sendMultipartTextMessage : " + message);
    	
    	smsManager.sendMultipartTextMessage(sendTo, null, partMessage, null, null);
    	
    	FLOG("finish sent : " + message);
    	
    	mSentPrevMessage = message;
    	mSentTick = mActivateTick;
    	
    	Time now = new Time();
    	now.setToNow();
    	String sn = now.format("%Y%m%d %k:%M:%S");
    	
    	FLOG("items add : " + message);
    	
    	if (MainActivity.items != null)
    	{
    		FLOG("MainActivity.items.add");
        	
    		MainActivity.items.add(sn + ">" + message);
    		
    	}
    	/*
    	if (MainActivity.adapter != null)
        {
    		FLOG("notifyDataSetChanged");
        	
    		MainActivity.adapter.notifyDataSetChanged();
    	}
    	*/
    	FLOG("adapter notifyDataSetChanged : " + message);
    	
    	return true;
	}
	
	public static final String PREFS_NAME = "WChildPrefsFile";
	public static final long MINIMUM_MESSAGE_GAP = 5000;
	public static final long MINIMUM_TRACE_GAP = 8000;
	public static final long MINIMUM_RESENT_GAP = 60000;
	public static final long MINIMUM_TRACE_RESENT_GAP = 1800000;
	
    private NotificationManager  mManager; 
	private Notification.Builder mBuilder;
	
	static public boolean mOnWorking = false;
    private SharedPreferences mSettings;
	
    private static Timer timer = new Timer(); 
    
    private long mActivateTick;
    
	LocationManager locationManager;

	private ActivityManager mActivityManager;
	
	String mSentPackageName;
	private long mBeginTraceTick;
	private long mTraceTick;
	
	String mSentPrevMessage;
	private long mSentTick;
	            	

    // Unique Identification Number for the Notification.
    // We use it on Notification start, and to cancel it.
    private int NOTIFICATION = 91023;
    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
    	SService getService() {
            return SService.this;
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    
    double _latitude, _longitude;
    
    @Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
	
		_latitude = (double) (location.getLatitude());
		_longitude = (double) (location.getLongitude());
	}    
	
    
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }


    
    @Override
    public void onCreate() {
    	mManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      	mBuilder = new Notification.Builder(this);
    
       	
        // Display a notification about us starting.  We put an icon in the status bar.
        showNotification();
        
    	mSettings = getSharedPreferences(PREFS_NAME, 0);
    	
       	if (Build.BRAND.equalsIgnoreCase("generic")) 
       	{
       	   // emulator
       	} else {
       	
       	}
       	
       	
       	locationManager = (LocationManager)
       			getSystemService(Context.LOCATION_SERVICE);
       	
       	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
       	
    	mActivityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
        
    	
       	mOnWorking = true;
       	
       	
       	
        timer.scheduleAtFixedRate(new mainTask(), 0, MINIMUM_MESSAGE_GAP);
        
        
        
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    	
    	timer.cancel();
        // Cancel the persistent notification.
    	mManager.cancel(NOTIFICATION);

        // Tell the user we stopped.
        Toast.makeText(this, "sservice_stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

    /**
     * Show a notification while this service is running.
     */
    @SuppressLint("NewApi")
	private void showNotification() {
      	mBuilder.setSmallIcon(R.drawable.ic_launcher);
       	mBuilder.setTicker("withchild service on");
       	mBuilder.setWhen(System.currentTimeMillis());
       	mBuilder.setContentText("withchild in cubesugar 2014 project");
       	mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
       			//Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
       	mBuilder.setAutoCancel(true);
       	//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, ItemListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
       	//mBuilder.setContentIntent(pendingIntent);
      		 
       	//mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
       	
        // Send the notification.
    	//mManager.notify(NOTIFICATION, mBuilder.build());
    }
    
	private class mainTask extends TimerTask
    { 
        public void run() 
        {
        	boolean mAuto = mSettings.getBoolean("autoActivation", true);
			
         	if (mAuto == true)
         	{
         	
         		long t = SystemClock.elapsedRealtime();
             	
         		Context context = getApplicationContext();	
         	     
         		PackageManager pm = context.getPackageManager();
         		 
         		int flags = PackageManager.GET_META_DATA;
   		    
    		    List<ApplicationInfo> applications = pm.getInstalledApplications(flags);
    		    //ApplicationInfo.FLAG_INSTALLED FLAG_IS_GAME
    		    
    		    long now = System.currentTimeMillis();
    		    
    		    for (ApplicationInfo appInfo : applications) {
    		         if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
    		             // System application
    		         }
    		         else if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) == 1)
    		         {
    		        	// _sendSMS(appInfo.packageName + " is installing now");
    		         }
    		         else 
    		         {
    		        	 long installed = 0;
    		          	 try {
							 installed = pm.getPackageInfo(appInfo.packageName,0).firstInstallTime;
				
							 if (now - installed < MINIMUM_MESSAGE_GAP
									 && now - installed >= 0)
	    		          	 {
	    		          		boolean r =_sendSMS(appInfo.packageName + " is installing now"
	    		          				+ " http://play.google.com/store/apps/details?id="
	    		          				+  appInfo.packageName 
	    		          				);
	        		         
	    		          		if (r == true) 
	    		          			break;
	    		          	 }
							 
    		          	 } catch (NameNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
    		          	
    		         }
    		    }
    		    
    		    if ( t - mActivateTick < MINIMUM_TRACE_GAP)
    		    {
    		    	return;
    		    	
    		    }
    		    
    		    String name = mSettings.getString("tracePackageName","empty");
	        	FLOG("tracePackageName -->" + name+ "<--");
    		    
	        	if (name == "empty")
	        		return;
	        		
	        	if (name == mSentPackageName)
	        	{
	        		//keep tracing
	        		
	        		String packageName = mActivityManager.getRunningTasks(1).get(0).topActivity
	                        .getPackageName();
	        		if (name.equals(packageName))
	        		{
	        			if (MINIMUM_TRACE_RESENT_GAP < t - mTraceTick)
	        			_sendSMS(name + " is still working for about" 
	        					+ (t - mBeginTraceTick)/(1000*60.0f) 
	        					+ " minutes.");
	        			
	        			mTraceTick = t;
	        		}
	        		else
	        		{
	        			_sendSMS(name + " is not working anymore ^-^");
	        			mSentPackageName = null;
	        		}
	        	}
	        	else
	        	{
	        		//new one
    		    	FLOG(name);
    		    	
	         		List<ActivityManager.RecentTaskInfo> info = mActivityManager.getRecentTasks(1, Intent.FLAG_ACTIVITY_NEW_TASK);
	
	         		RecentTaskInfo recent = info.get(0);
	         		Intent mIntent = recent.baseIntent;
	         		String appString = mIntent.getComponent().getPackageName();
	         	    
	         		FLOG("appString -->" + appString + "<--");
	         		
	         		if (name.equals(appString))
	         		{
	         			
	         			_sendSMS(name + " is working on child's phone now"
	         					+ " http://play.google.com/store/apps/details?id="
		          				+  name
	         					);
	         			mSentPackageName = name;
	         			mBeginTraceTick = t;
	         			mTraceTick = t;
	         		}
    		    }
    		    
         		//long installed = context.getPackageManager().getPackageInfo("package.name", 0).firstInstallTime;
         
    		    mActivateTick = t;
         	}
         	
        }
    }    
	
}

